package com.qf.czh.vhr.Service;

import com.qf.czh.vhr.Mapper.PositionMapper;
import com.qf.czh.vhr.entity.Position;
import com.qf.czh.vhr.entity.RespPageBean;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PositionService {
    @Autowired
    PositionMapper positionMapper;
    @Autowired
    SqlSessionFactory sqlSessionFactory;
    public List<Position> getAllPositions() {
       List<Position> list =  positionMapper.getAllPositions();
       return list;

    }

    public Integer addPosition(Position position) {
        Position p = positionMapper.getPositionByName(position.getName());
            if (p != null){
                return -1;
            }
            position.setCreateDate(new Date());
            position.setEnabled(true);
            Integer i = positionMapper.addPosition(position);
            return i;
    }

    public Integer deletePositionByid(Integer id) {
        Integer i = positionMapper.deletePositionById(id);
            return i;
    }

    public Integer updatePosition(Position position) {

        Integer i = positionMapper.updatePosition(position);
        return i;
    }

    public void addPositionBatch(List<Position> positions) {
        System.out.println(positions);
        //上面注入的positionMapper 不具备批量操作, 指明获取一个具备批量操作的sqlSession来过去mapper
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        //获取mapper
        PositionMapper positionMapper = sqlSession.getMapper(PositionMapper.class);
        //通过for循环,用刚刚的mapper来添加position 方法还是原来的方法.只是具备了批量
        for (Position position:positions) {
            System.out.println(position);
            positionMapper.addPosition(position);
        }

        sqlSession.commit();

    }

    public RespPageBean getPositionByPage(Integer page, Integer size) {
        Integer p = (page-1)*size;
       List<Position> list =  positionMapper.getPositionByPage(p , size);
       RespPageBean respPageBean = new RespPageBean();
       respPageBean.setData(list);
        long total = positionMapper.getTotal();
        respPageBean.setTotal(total);
        return respPageBean;
    }
}
